package com.excel.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class Excel2007 {

	private static XMLReader xmlReader = null;
	public static List<String> getSheetNames(InputStream is)throws Exception{
		final List<String> sheetNames= new ArrayList<String>();
		OPCPackage pkg = OPCPackage.open(is);
		XSSFReader r = new XSSFReader( pkg );
		XMLReader parser = getXMLReader();
		parser.setContentHandler(new DefaultHandler(){
			@Override
			public void startElement(String uri, String name,
					String qName, Attributes attributes) throws SAXException {
				if("sheet".equals(name)){
					sheetNames.add(attributes.getValue("name"));
				}
			}
		});
		is = r.getWorkbookData();
		parser.parse(new InputSource(is));

		return sheetNames;
	}
	
	private static XMLReader getXMLReader() throws SAXException {
		if(xmlReader!=null){
			return xmlReader;
		}
		XMLReader parser =
			XMLReaderFactory.createXMLReader(
					"org.apache.xerces.parsers.SAXParser"
			);
		return parser;
	}
	
	public static void main(String[] args)throws Exception {
		String root = "/home/supertool/share/a.xlsx";
		List<String> names = getSheetNames(new FileInputStream(root));
		if(names!=null){
			for(String name :names){
				System.out.println(name);
			}
		}
	}
}
